<?php

namespace V1\Model;


use Think\Model;

class IntegralModel extends Model
{
    protected $tableName = 'expert_profile';

    /**
     * 获取积分等级所对应的积分
     * @param  $userid [用户id]
     * @return mixed
     */
    public function get_grade($userid, $field = array())
    {
        $integral = M('integral_grade');
        $map['userid'] = !empty($userid) ? $userid : "";
        $data = $integral->field($field)->select();
        return $data;
    }

    /**
     * 获取积分对应的等级
     * @param $score [积分]
     * @param $id [用户id]
     * @return int|string
     */
    public function grade_type($score, $id)
    {
        $request = $this->get_grade($id);
        $num = count($request);
        foreach ($request AS $key => $value) {
            if ($score >= $request[0]['integral']) {
                if ($request[$key]['grade_id'] < $num) {
                    if ($score > $request[$key]['integral'] && $score <= $request[$key + 1]['integral']) {
                        $level = $request[$key + 1]['grade_id'];
                        break;
                    } else if ($score > $request[$num - 1]['integral']) {
                        $level = $request[$num - 1]['grade_id'];
                        break;
                    }
                }
            } else {
                $level = $request[0]['grade_id'];
            }
        }
        return $level;
    }

    /**
     * 设置会员等级
     * @param $score [会员积分]
     * @param $userid [用户id]
     * @return string  返回用户等级
     */
    public function set_member_grade($score, $userid)
    {
        $limit = ['grade_id', 'integral'];
        $data = $this->get_grade($userid, $limit);
        $num = count($data);
        $grade = '';
        foreach ($data AS $key => $value) {
            if ($score >= $data[0]['integral']) {
                if ($data[$key]['grade_id'] < $num) {
                    if ($score > $data[$key]['integral'] && $score <= $data[$key + 1]['integral']) {
                        $grade = $data[$key + 1]['grade_id'];
                        break;
                    } else if ($score > $data[$num - 1]['integral']) {
                        $grade = $data[$num - 1]['grade_id'];
                        break;
                    }
                }
            } else {
                $grade = $data[0]['integral'];
            }
        }
        return $grade;
    }

}